﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iwss.Document.Layouts.AjaxServices;
using System.Web;
using Microsoft.SharePoint;
using System.Collections;

namespace iwss.Document.Layouts.Services
{
    public class FileAction : IAjaxService
    {
        public SPList ShareLib { get { return SPContext.Current.Web.Lists.TryGetList("共享库"); } }
        public SPList DocLib { get { return SPContext.Current.Web.Lists.TryGetList("文档库"); } }
        public string CurrentUserDocumentZoneAddress { get { return string.Format("{0}/{1}", DocLib.RootFolder.Url, Utilitys.GetUserName(SPContext.Current.Web.CurrentUser.Name)); } }

        public AjaxResult Excute(HttpContext context)
        {
            string ActionType = context.Request["act"].ToLower();
            AjaxResult result = null;

            switch (ActionType)
            {
                case "get":
                    result = GetUserFiles(context);
                    break;
                case "delete":
                    result = DeleteUserFile(context);
                    break;
                case "folder":
                    result = GetUserFolders(context);
                    break;
            }

            return result;
        }

        private AjaxResult DeleteUserFile(HttpContext context)
        {
            List<string> recids = Utility.Asy(context.Request["ids"]);
            string ct = context.Request["ct"];
            var lib = ct == "file" ? DocLib : ShareLib;

            int id = -1;
            lib.ParentWeb.AllowUnsafeUpdates = true;
            foreach (string item in recids)
            {
                if (item.IsNullOrEmpty()) continue;
                if (int.TryParse(item, out id))
                {
                    SPListItem listitem = lib.GetItemById(id);
                    if (listitem == null) continue;

                    listitem.Delete();
                }
            }
            lib.ParentWeb.AllowUnsafeUpdates = false;

            return new AjaxResult(true, "OK");

        }

        private AjaxResult GetUserFolders(HttpContext context)
        {
            SPFolder folder = GetSPFolder("");
            SPFolderCollection folders = folder.SubFolders;
            ArrayList res = new ArrayList();
            foreach (SPFolder item in folders)
            {
                res.Add(new
                {
                    Name = item.Name,
                    Url = HttpUtility.UrlEncode(item.ServerRelativeUrl)
                });
            }

            return new AjaxResult(true, res)
            {
                Addition = new
                {
                    FolderUrl = folder.ServerRelativeUrl,
                    ListID = DocLib.ID
                }
            };
        }

        private AjaxResult GetUserFiles(HttpContext context)
        {
            string addction = context.Request["folder"];
            string subfolder = context.Request["subfolder"];
            SPFolder folder = GetSPFolder(addction);

            SPFileCollection files = folder.Files;
            SPFolderCollection folders = folder.SubFolders;

            int itemCount = files.Count;
            ArrayList resFile = new ArrayList();
            ArrayList resFolder = new ArrayList();

            for (int i = 0; i < itemCount; i++)
            {
                SPFile file = files[i];
                resFile.Add(new
                {
                    Title = file.Name,
                    ItemID = file.Item.ID,
                    CheckBox = true,
                    FileID = file.UniqueId,
                    UniqueId = file.UniqueId,
                    Url = file.ServerRelativeUrl,
                    ModifyTime = file.TimeLastModified,
                    Icon = Utilitys.GetIcon(file.ServerRelativeUrl),
                    attr = new { target = "_blank" }
                });
            }

            foreach (SPFolder item in folders)
            {
                resFolder.Add(new
                {
                    Name = item.Name,
                    Url = HttpUtility.UrlEncode(item.ServerRelativeUrl)
                });
            }

            if (folder.Item.ParentList.RootFolder.Url != folder.ParentFolder.Url)
            {
                resFile.Add(new
                {
                    Title = "返回上一层",
                    ItemID = string.Empty,
                    CheckBox = false,
                    FileID = string.Empty,
                    UniqueId = string.Empty,
                    Icon = "/_layouts/iwss.Document/images/up.jpg",
                    Url = "javascript:iwss.action.up()",
                    ModifyTime = string.Empty,
                    attr = new { target = "" }
                });
            }

            return new AjaxResult(true, null)
            {
                Data = new
                {
                    Files = resFile,
                    Folders = resFolder
                },
                Addition = new
                {
                    FolderUrl = folder.ServerRelativeUrl,
                    ListID = DocLib.ID
                }
            };
        }

        private SPFolder GetSPFolder(string folder)
        {
            string temp = string.Empty;
            if (folder.IsNullOrEmpty())
                temp = CurrentUserDocumentZoneAddress;
            else
                temp = folder;

            SPFolder spfolder = SPContext.Current.Web.GetFolder(temp);
            if (!spfolder.Exists)
            {
                SPFolder newFolder = Utilitys.CreateSPFolder(temp); //DocLib.RootFolder.SubFolders.Add(temp); //
                newFolder.ParentWeb.AllowUnsafeUpdates = true;
                newFolder.SubFolders.Add("我的文档");
                newFolder.SubFolders.Add("常用资料");
                newFolder.SubFolders.Add("课件");
                newFolder.ParentWeb.AllowUnsafeUpdates = false;
                return newFolder;
            }

            return spfolder;
        }
    }
}
